package org.web.common.sso.server.biz;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web.base.domain.ResultDO;
import org.web.base.domain.helper.ServiceExceptionHelper;
import org.web.common.sso.server.config.SSOServerConfig;
import org.web.common.sso.server.controller.SessionAccountController;
import org.web.common.sso.server.helper.redis.CacheSessionDO;
import org.web.common.sso.server.query.QuerySsoToken;

import javax.annotation.Resource;

public class BothTokenBizImpl extends AbstractTokenBiz {

    private static boolean OCCURRED_ERROR = false;

    Logger logger = LoggerFactory.getLogger(SessionAccountController.class);
    @Resource
    private SSOServerConfig ssoServerConfig;

    @Resource
    private AbstractTokenBiz databaseTokenBiz;

    @Resource
    private AbstractTokenBiz redisTokenBiz;

    @Override
    public ResultDO<CacheSessionDO> exchangeToken(String token) {
        ResultDO<CacheSessionDO> resultDO = new ResultDO<>();
        QuerySsoToken querySsoToken = new QuerySsoToken();
        querySsoToken.setSsoToken(token);
        if (Boolean.TRUE.equals(ssoServerConfig.getHasRedis())) {
            try {
                resultDO = redisTokenBiz.exchangeToken(token);
            } catch (Exception e) {
                logger.error(ServiceExceptionHelper.getExceptionInfo(e));
                return databaseTokenBiz.exchangeToken(token);
            }
        }
        return resultDO;
    }

    @Override
    public void refreshToken(String token, CacheSessionDO cacheSessionDO) {
        cacheSessionDO.setLastMarkTime(System.currentTimeMillis());// 数据库update-time等同于放入缓存lastMark-time。
        if (Boolean.TRUE.equals(ssoServerConfig.getHasRedis())) {
            try {
                redisTokenBiz.refreshToken(token, cacheSessionDO);
            } catch (Exception e) {
                logger.error(ServiceExceptionHelper.getExceptionInfo(e));
                databaseTokenBiz.refreshToken(token, cacheSessionDO);
            }
        }
    }

}
